

import Taro from "@tarojs/taro";

export const getStorageData = async (key: string) => {
  let result: any;
  try {
    const { data } = await Taro.getStorage({ key });
    result = data;
  } catch (error) {
    console.log(error);
  }
  return result;
};

// num为传入的值，n为保留的小数位
export const fomatFloat = (num: number | string, n: number) => {
  let f = parseFloat(num as string);
  if (Number.isNaN(f)) {
    return false;
  }
  f = Math.round((num as number) * Math.pow(10, n)) / Math.pow(10, n); // n 幂
  return f;
};


export const dateFormat = function (date:Date,fmt:string) { 
  var o = {
      "M+": date.getMonth() + 1, // 月份 
      "d+": date.getDate(), // 日 
      "h+": date.getHours(), // 小时 
      "m+": date.getMinutes(), // 分 
      "s+": date.getSeconds(), // 秒 
      "q+": Math.floor((date.getMonth() + 3) / 3), // 季度 
      "S": date.getMilliseconds() // 毫秒 
  };
  if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
  for (var k in o)
  if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
  return fmt;
};


export const strDateFormat = function (d:string,fmt:string) { 
  d = d.replace(/-/g,"/");
  var date = new Date(d);
  var o = {
      "M+": date.getMonth() + 1, // 月份 
      "d+": date.getDate(), // 日 
      "h+": date.getHours(), // 小时 
      "m+": date.getMinutes(), // 分 
      "s+": date.getSeconds(), // 秒 
      "q+": Math.floor((date.getMonth() + 3) / 3), // 季度 
      "S": date.getMilliseconds() // 毫秒 
  };
  if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
  for (var k in o)
  if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
  return fmt;
};


export const  getFileType = (name)=> {
  if(!name) return "unknow";
  var imgType = ["gif", "jpeg", "jpg", "bmp", "png"];
  var videoType = ["avi","wmv","mkv","mp4","mov","rm","3gp","flv","mpg","rmvb"];
  if(RegExp("\.(" + imgType.join("|") + ")$", "i").test(name.toLowerCase())) {
     return "image";
  } else if(RegExp("\.(" + videoType.join("|") + ")$", "i").test(name.toLowerCase())) {
     return "video";
  } else {
   return "unknow";
  }
};


export const durationFormat = (milliseconds:number)=>{
  const timeArr:Array<string> = [];
  let millis = milliseconds % 60 + "";
  let seconds = Math.floor(milliseconds / 60) + "";
  seconds = seconds.length < 2 ? "0" + seconds : seconds;
  millis = millis.length < 2 ? "0" + millis : millis;
  timeArr.push(seconds + "");
  timeArr.push(millis + "");
  return timeArr.join(":");
};